<?php

if(!is_cli()){
	if (!defined("WEB_HOST")) {
		define('WEB_HOST', 'http://' . $_SERVER['HTTP_HOST']. DIRECTORY_SEPARATOR) ;
	}
}

function is_cli(){
     return preg_match("/cli/i", php_sapi_name()) ? true : false;
}

/**
 * 获取数据的所有子孙数据的id值
 */
function get_stemma($pids, $table, $field='id', $has_pid = false){
	static $ids = [];
	$child_ids  = [];

	//非空判断
	if(empty($pids)){
		return $ids;
	}

	if( !is_array($pids)){
		$pids = [$pids];
	}
	$result = DB::table($table)->select('id')->whereIn( 'pid', $pids)->get()->toArray();
	if(!$result){
		if($has_pid){
			$ids = array_merge($pids, $ids);
		}
		return $ids;
	}
	foreach($result as $v){
		$child_ids[] = $v->id;
	}
	$ids = array_merge($ids, $child_ids);

	get_stemma($child_ids, $table);

	if($has_pid){
		$ids = array_merge($pids, $ids);
	}

	return $ids;
}

/**
 * 根据子孙id获取所有上级的id
 */
function get_shop_root($id, $table, $next = false){
	static $ids = [];
	static $arr = [];
	$child_ids  = [];
	if($next){
		$arr = [];
	}

	//非空判断
	if(empty($id)){
		return $ids;
	}

	if( !is_array($id)){
		$id = [$id];
	}
	$result = DB::table($table)->select('pid','shop_name')->whereIn( 'id', $id)->get()->toArray();
	if(!$result){

		return $ids;
	}
	foreach($result as $v){
		$child_ids[] = $v->pid;
		$arr[] = $v->shop_name;
	}
	$ids = array_merge($ids, $child_ids);

	get_shop_root($child_ids, $table);

	if(is_array($arr)){
		$tmp = $arr;
		// 除去当前店铺
		unset($tmp[0]);

		$new_arr = array_reverse($tmp);
		$str = implode('>', $new_arr);
		static $arr = [];
		return $str;
	}
	return '';

}


/**
 * 插入数据处理，null值变为空值
 */
function input_data($request, $except = []){
	$data = [];
	foreach($request->all() as $k =>$v){
		if(!is_null($v) && !in_array($k, $except)){
			$data[$k] = $v;
		}
	}
	return $data;
}

/**
 * 图片转换
 */
function t_img($path, $flag = ''){
	if(stristr($path, 'http') || stristr($path, 'ueditor')){
		return $path;
	}else{
		if(empty($path)){
			return $path;
		}
		$arr = explode('.',  $path);
		if($flag == 1){
			$url = WEB_HOST . $arr[0] . '_1.' . $arr[1];
		}else if($flag == 2){
			$url = WEB_HOST . $arr[0] . '_2.' . $arr[1];
		}else{
			$url = WEB_HOST . $path;
		}
		return str_replace('\\','/',$url);
	}
}

/**
 * 获取集合的id
 */
function get_ids($arr, $field = 'id', $is_array = false){

	$ids = [];
	foreach($arr as $v){
		if($is_array){
			$ids[] = $v[$field];
		}else{
			$ids[] = $v->$field;
		}
	}
	return array_unique( $ids );
}

/**
 * 数据格式化
 */
function data_format($arr, $keys, $is_array = false) {
    if (!is_array($keys)) {
        $keys = array($keys);
    }
    if (!is_array($arr)) {
        return $arr;
    }
    $new = array();
    foreach ($arr as $value) {
        $tmp_new = array();
        foreach ($keys as $v) {
            if($is_array){
                $tmp_new[] = $value[$v];
            }else{
                $tmp_new[] = $value->$v;
            }
        }
        $tmp_new = implode($tmp_new, '_');
        $new[$tmp_new] = $value;
    }
    return $new;
}

/**
 * http 请求
 */
function https_request($url,$data = null, $rtn_arr = false, $is_json = false){

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

    if (!empty($data)){
        if ($is_json){
            $data = json_encode($data);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json',
                    'Content-Length: ' . strlen($data))
            );
        }

        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    if($rtn_arr){
        return json_decode($output, true);
    }
    return $output;
}



/**
 * 设置表一列的默认值为空
 */
function set_table_value($table) {
	$data = (object)[];
	$columns = Schema::getColumnListing($table);
	if(empty($columns)){
		return $data;
	}
	foreach($columns as $v){
		$data->$v = '';
	}
	return $data;
}

/**
 * 获取当前控制器与方法
 *
 * @return array
 */
if(!function_exists('getCurrentAction')){
    function getCurrentAction($is_str = false){
        $action = \Route::current()->getActionName();
		if(strpos('@', $action) === false){
			return '';
		}
        list($class, $method) = explode('@', $action);
        $class = substr(strrchr($class,'\\'),1);
		$arr = explode('\\', $action);
		if($is_str){
			$class = str_ireplace('Controller', '', $class);
			$str = $arr[3]. $class . $method;
			$str = strtolower($str);
			return md5($str);
		}
        return ['module' => $arr[3],'controller' => $class, 'method' => $method];
    }
}

/**
 * 获取当前控制器名
 *
 * @return string
 */
if(!function_exists('getCurrentControllerName')){
    function getCurrentControllerName(){
        return getCurrentAction()['controller'];
    }
}

/**
 * 获取当前方法名
 *
 * @return string
 */
if(!function_exists('getCurrentMethodName')){
    function getCurrentMethodName(){
        return getCurrentAction()['method'];
    }
}

/**
 * 验证是否是手机号
 */
function isPhone($phone) {
    if (!is_numeric($phone)) {
        return false;
    }
    return preg_match('#^1[0-9]{10}$#', $phone) ? true : false;
}

/**
 * 获取guid
 */
function guid() {
    if (function_exists('com_create_guid')) {
		return com_create_guid();
    } else {
        mt_srand((double)microtime()*10000);
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $hyphen = chr(45);
        $uuid   = substr($charid, 0, 8).$hyphen
                 .substr($charid, 8, 4).$hyphen
                 .substr($charid,12, 4).$hyphen
                 .substr($charid,16, 4).$hyphen
                 .substr($charid,20,12)
                 ;
        return $uuid;
    }
}

/**
 * 将 xml数据转换为数组格式。 ihuyi 短信需要
 */
function xml_to_array($xml){
	$reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
	if(preg_match_all($reg, $xml, $matches)){
		$count = count($matches[0]);
		for($i = 0; $i < $count; $i++){
		$subxml= $matches[2][$i];
		$key = $matches[1][$i];
			if(preg_match( $reg, $subxml )){
				$arr[$key] = xml_to_array( $subxml );
			}else{
				$arr[$key] = $subxml;
			}
		}
	}
	return $arr;
}

/**
 * 发送短信
 */
function send_sms($mobile, $content){
	//短信接口地址
	$target = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";

	$post_data = "account=cf_lctuangou&password=53133bc442e26e77ee8dd33d1c5087cd&mobile=".$mobile."&content=".rawurlencode($content);
	//用户名是登录用户中心->验证码短信->产品总览->APIID
	//查看密码请登录用户中心->验证码短信->产品总览->APIKEY
	$gets =  xml_to_array(https_request($target, $post_data));

	$rtn['code'] = $gets['SubmitResult']['code'] == 2 ? '0' : '1002';
	$rtn['msg'] = $gets['SubmitResult']['msg'];
	return $rtn;
}

/**
 * 排序数组
 */
function multi_array_sort($multi_array,$sort_key,$sort=SORT_ASC) {
    //if(is_array($multi_array)) {
        foreach ($multi_array as $row_array) {
            //if(is_array($row_array)) {
                $key_array[] = $row_array->$sort_key;
            //} else {
            //    return false;
            //}
        }
    //}else{
    //    return false;
    //}
    array_multisort($key_array,$sort,$multi_array);
    return $multi_array;
}

/**
 * 得到order_sn
 */
function get_order_sn() {
	return date('YmdHis') . mt_rand(100000, 999999);
}

/**
 * 给用户弹一个错误
 */
function alert_error($error) {
    echo <<< EOT
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no" />
    <title>error</title>
</head>
<body>
EOT;
    echo '<script>alert(\'' . $error . '\');history.go(-1);</script></body></html>';
    exit;
}

/**
 * 写日志
 */
function write_log($file, $msg, $data){

	$data = var_export($data, true);

	$dir = WEB_PATH . DIRECTORY_SEPARATOR . 'Data' . DIRECTORY_SEPARATOR;
	if(!is_dir($dir)){
		mkdir($dir, 0777, true);
	}

    $file = $dir . $file . '_' . date('Ymd') . '.log';

    $time = date("Y-m-d H:i:s");
    $data = "【" . $time . "】" . $msg . "\n" . $data . "\n";
    file_put_contents($file, $data, FILE_APPEND);
}

/**
 * 是否微信浏览器
 * @return bool
 */
function is_wechat_browser() {
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    if (strpos(strtolower($user_agent), 'micromessenger') === false) {
        return false;
    } else {
        return true;
    }
}





















